/**
 * MySpace(China) Javascript Utility for Reference by UI Team
 * 
 * @author KCZ
 * @version 0.1
 */

var K = {
	/*
	 * xDom
	 * */
	byClass:function(asClass, aeP, asTag){
	    var lxNew = [];
	    asClass = asClass == null ? "" : asClass;
	    aeP = aeP == null ? document : aeP;
	    asTag = asTag == null ? "*" : asTag;
	    
	    var lxTag = aeP.getElementsByTagName(asTag);
	    var pattern = new RegExp("(^|\s)" + asClass + "(\s|$)");
	    for (var i = 0; i < lxTag.length; i++) {
	        if ((" " + lxTag[i].className + " ").indexOf(" " + asClass + " ") != -1) {
	            lxNew.push(lxTag[i]);
	        }
	    }
	    return lxNew;
	},
	hasClass:function(aeTag){
	    if (!aeTag || !aeTag.className) {
	        return false;
	    }
	    if ((" " + aeTag.className + " ").indexOf(" " + asClass + " ") == -1) {
	        return false;
	    }
	    return true;		
	},
	addClass:function(aeTag, asClass){
	    asClass = asClass == null ? 'cnViOver' : asClass;
	    if ((" " + aeTag.className + " ").indexOf(" " + asClass + " ") == -1) {
	        aeTag.className = (aeTag.className + ' ' + asClass).replace(/(^\s*)|(\s*$)/g, "");
	    }
	    return aeTag;
	},
	removeClass:function(aeTag, asClass){
	    asClass = asClass == null ? 'cnViOver' : asClass;
	    aeTag.className = aeTag.className.replace(new RegExp('(^|\\s)' + asClass + '(?:\\s|$)'), '$1').replace(/(^\s*)|(\s*$)/g, "");
	},
	getEvent:function(afEvent){
		if(!afEvent){
			return null;
		}
		if(window.event){
			return window.event;
		}
		var lfEvent = afEvent.caller;
		while(lfEvent != null){
			var loEvent = lfEvent.arguments[0];
			if(loEvent && loEvent.constructor == MouseEvent){
				return loEvent;
			}
			lfEvent = lfEvent.caller;
		}
		return null;
	},
	addEvent:function(aeTag, asEvt, afHandler){
	    if (!aeTag) {
	        return false;
	    }
	    if (navigator.userAgent.indexOf("IE") != -1) {
	        aeTag.attachEvent("on" + asEvt, afHandler);
	    } else {
	        aeTag.addEventListener(asEvt, afHandler, false);
	    }
	},
	removeEvent:function(aeTag,asEvt,afHandler){
	    if(!aeTag){
	        return false;
	    }
	    if(navigator.userAgent.indexOf("IE")!=-1){
	        aeTag.detachEvent("on"+asEvt,afHandler);
	    }else{       
	        aeTag.removeEventListener(asEvt,afHandler,false);
	    }
	},
	/*
	 * xPage
	 * */
	 /**
	  * Finding the Current Position of the Mouse Cursor Within the Entire Web Page
	  */
	getMouse:function(event){
		event = event || windiow.event;
		var isIE = navigator.userAgent.indexOf("IE")!=-1;
		return {
			x: isIE ? event.clientX + document.documentElement.scrollLeft : event.pageX,
			y: isIE ? event.clientY + document.documentElement.scrollTop : event.pageY
		};
	},
	 /**
	  * Testing!!!
	  * Retreiving the Position of the Mouse Relative to the Current Element
	  */
	getMouseInElement:function(event){
		return {
			x: (event && event.layerX) || window.event.offsetX,
			y: (event && event.layerY) || window.event.offsetY
		};
	},
	 /**
	  * Deternming the Length and the Width of the Current Web Page
	  */
	getPageSize:function(){
		var lsObj;		
		if(navigator.userAgent.indexOf("IE")!=-1){
			lsObj = "documentElement";
		}else{
			lsObj = "body";
		}
		return{
			x: document[lsObj].scrollWidth,
			y: document[lsObj].scrollHeight
		};
	},
	 /**
	  * Deternming How Far the Browser Is Scrolled
	  * the first part is for IE, and other browsers will return 0
	  */
	getScroll:function(){
		var lsObj;		
		if(navigator.userAgent.indexOf("IE")!=-1){
			lsObj = "documentElement";
		}else{
			lsObj = "body";
		}
		return{
			x: document[lsObj].scrollLeft,
			y: document[lsObj].scrollTop
		};			
	},
	 /**
	  * Deternming the Height and Width of the Browser Viewport
	  * document.bodyElement.clientWidth will return right value in IE, while Firefox will return the width of the whole page 
	  */
	getViewPort:function(){
		var lsObj;		
		if(navigator.userAgent.indexOf("IE")!=-1){
			lsObj = "documentElement";			
		}else{
			lsObj = "body";
		}
		return{
			x: document[lsObj].clientWidth,
			y: document[lsObj].clientHeight
		};
		/**
		if(navigator.userAgent.indexOf("IE")!=-1){
			return{
				x: document.documentElement.clientWidth,
				y: document.documentElement.clientHeight
			};
		}else{
			return{
				x: self.innerWidth,
				y: self.innerHeight
			};
		}		 
		 */
	},
	/**
	 * Maximize Window
	 */
	maxWindow:function(){
		self.moveTo(0,0);
		self.resizeTo(screen.availWidth,screen.availHeight);
	},
	getTarget:function(event){
	    event = event || window.event;
	    return event.target || event.srcElement;
	},
	setOpacity:function(aeNode,aiLevel){
		if(aeNode.filters){
			aeNode.style.filters = 'alpha(opacity=' + aiLevel + ')';
		}else{
			aeNode.style.opacity = aiLevel / 100;
		}
	},
	getParameter:function(asName){
	    var reg = new RegExp("(^|&|\\?|\\s)"+ asName +"\\s*=\\s*([^&]*?)(\\s|&|$)", "i");
	    if (reg.test(document.location.search)){
	    	 return RegExp.$2.replace(/[\x0f]/g, ";");
	    }
	    return "";
	},
	totalLength:function(asStr){
	    var liLength=0;
	    if(asStr!=""){
	        for(var i=0;i<asStr.length;i++){ 
	            var code=escape(asStr.charAt(i)); 
	            if((code.length>=4)&&(code<'%uFF60'||code>'%uFF9F')){ 
	                liLength+=2; 
	            }else{
	                liLength++; 
	            }
			} 
	    }
	    return liLength; 
	},
	trim:function(asStr){
	    asStr = asStr == null ? "" : asStr;
	    return asStr.replace(/(^\s*)|(\s*$)/g, "");
	},
	getStyle:function(aeNode,asName){
	    if (typeof(aeNode)=="string"){
			 aeNode=document.getElementById(aeNode);
		}
		var lsIE,lsW3C;
		if(asName.indexOf("-")!=-1){
			lsW3C = asName;
			// to be improved
	        lsIE = asName.split("-")[0]+asName.split("-")[1].charAt(0).toUpperCase()+asName.split("-")[1].substring(1);
		}else{
			lsIE = asName;
	        lsW3C = asName.replace(/([A-Z])/g, "-$1");
		}
	    return navigator.userAgent.indexOf("IE")!=-1 ?aeNode.currentStyle[lsIE]:document.defaultView.getComputedStyle(aeNode, "").getPropertyValue(lsW3C);
	},	
	smartView:function(asHTML, axData){
	    var lxLeft = asHTML.split("{K:");
	    var lxHTML = [];
	    if(!axData){
	    	return false;
	    }
		if(axData.constructor != Array){
			if(axData.constructor == Number){
				var liIndex = axData;
				axData = [];				
				axData[liIndex - 1] = {};
			}else{
				axData = [axData];	
			}
		}
	    for (var i = 0; axData && i < axData.length; i++) {
	        for (var j = 0; j < lxLeft.length; j++) {
	            var lsProp = lxLeft[j].substring(0, lxLeft[j].indexOf("}"));
	            if (lsProp != "") {
	            	if(lsProp == "k"){            		
	            		lxHTML[lxHTML.length] = i;
	                	lxHTML[lxHTML.length] = lxLeft[j].substring(lxLeft[j].indexOf("}") + 1);
	            	}else{
	            		lxHTML[lxHTML.length] = axData[i][lsProp];
	                	lxHTML[lxHTML.length] = lxLeft[j].substring(lxLeft[j].indexOf("}") + 1);
	            	}
	               
	            }
	            else {
	                lxHTML[lxHTML.length] = lxLeft[j];
	            }
	        }
	    }
	    return lxHTML.join("");
	},
	copyToClipboard:function(asTxt) {   
		if(window.clipboardData) {   
			window.clipboardData.clearData();   
			window.clipboardData.setData("Text", asTxt);
			return true;
		} else if(navigator.userAgent.indexOf("Opera") != -1) {   
			window.location = asTxt;
			return true;
		} else if (window.netscape) {   
			try {   
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");   
			} catch (e) {   
	   			alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'"); 
				return false;
			}   
			var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);   
			if (!clip){
				return false;
			}   
				   
			var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);   
			if (!trans){
				return false;
			}   
				   
			trans.addDataFlavor('text/unicode');   
			var str = {};   
			var len = {};   
			var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);   
			var copytext = asTxt;   
			str.data = copytext;   
			trans.setTransferData("text/unicode",str,copytext.length*2);   
			var clipid = Components.interfaces.nsIClipboard;
			if (!clip){
				return false;
			}
			clip.setData(trans,null,clipid.kGlobalClipboard);
			return true;
		}   
	},
	/**
	 * @author KCZ
	 * @version 0.2
	 * 
	 * @param {Object} aeNode, dom node with animation
	 * @param {Object} asStyle, style property name,(e.g., marginLeft)
	 * @param {Object} aoOption
	 * 					{startVal: start value, default:0
	 * 					 endVal: end value, default: the exact value of the node style property
	 * 					 interval: interval time finishing animation, unit:milli-second, default: 1000
	 * 					}
	 * @method go, begin to show animation
	 * @method onEnd, the method is invoked at the end of the animation	 
	 */
	animation : function(aeNode,asStyle,aoOption){
		var obj = {}; 
		if(aeNode ==  null){return false;}
		if(aoOption == null){aoOption = {};}
		var lsPropName = asStyle || "width";
		var UNIT = 5;
		
		obj.node = aeNode;
		obj.style = asStyle || "width";		
		obj.startVal = aoOption.from || 0;
		// get default style property value of the node
		obj.endVal = aoOption.to || parseInt(navigator.userAgent.indexOf("IE")!=-1 ?aeNode.currentStyle[obj.style]:document.defaultView.getComputedStyle(aeNode, "").getPropertyValue(obj.style.replace(/([A-Z])/g, "-$1")));
		obj.interval = aoOption.interval || 1000;
		var liInterval;	
		obj.go = function(){
			if(obj.doing){return false;}
			liInterval = obj.interval / UNIT;
			obj.doing = true;
			for (var i = 0; i <= liInterval; i += UNIT) {repeater(i);}
		};
	
		function repeater(index){
			(function(){setTimeout(function(){
				aeNode.style[lsPropName] = (obj.startVal + Math.round((index / liInterval) * (obj.endVal - obj.startVal))) + "px";
				if(index == liInterval){
					aeNode.style[lsPropName] = obj.endVal;
					obj.doing = false;
					if(obj.onEnd){obj.onEnd();}
				}
			}, (index + 1) * UNIT);})();
		}
		return obj;
	}	
}
var KK = {
	/**
	 * 
	 * @param {Object} aeNode
	 * 
	 * @inherit K.getStyle
	 * 			K.getScroll
	 * 			K.getViewPort
	 */
	goCenter: function(aeNode){
		var leNode;
		if(typeof aeNode == "string"){
			leNode = document.getElementById(aeNode);
		}
		var lsPosition = K.getStyle(leNode,"position");
		var liWidthNode = parseInt(K.getStyle(leNode,"width"));
		var liHeightNode = parseInt(K.getStyle(leNode,"height"));

		leNode.style.position = "absolute";
		leNode.style.marginTop = "0px";
		leNode.style.marginLeft = "0px";
		leNode.style.left = Math.floor((K.getViewPort().x - liWidthNode) / 2)+K.getScroll().x + "px";
		leNode.style.top = Math.floor((K.getViewPort().y - liHeightNode) / 2)+K.getScroll().y + "px";
		
		K.addEvent(window,"resize",function(){KK.goCenter(aeNode);});
		K.addEvent(window,"scroll",function(){KK.goCenter(aeNode);});		
	}	
}

function cssQuery(selector, root){
	if(!selector){
		return [null];
	}	
    root = root == null ? document : root;
    root = typeof root == "string" ? document.getElementById("root") : root;
    // Attempt to fail gracefully in lesser browsers
    if (!document.getElementsByTagName) {
        return new Array();
    }
    // Split selector in to tokens
    var tokens = selector.split(' ');
    var currentContext = [root];
    for (var i = 0; i < tokens.length; i++) {
        token = tokens[i].replace(/^\s+/, '').replace(/\s+$/, '');
        if (token.indexOf('.') > -1) {
            // Token contains a class selector
            var bits = token.split('.');
            var tagName = bits[0];
            var className = bits[1];
            if (!tagName) {
                tagName = '*';
            }
            // Get elements matching tag, filter them for class selector
            var found = new Array;
            var foundCount = 0;
            for (var h = 0; h < currentContext.length; h++) {
                var elements;
                if (tagName == '*') {
                    var leNode = currentContext[h];
                    elements = leNode.all ? leNode.all : leNode.getElementsByTagName('*');
                } else {
                    elements = currentContext[h].getElementsByTagName(tagName);
                }
                for (var j = 0; j < elements.length; j++) {
                    found[foundCount++] = elements[j];
                }
            }
            currentContext = new Array;
            var currentContextIndex = 0;
            for (var k = 0; k < found.length; k++) {
                if (found[k].className && found[k].className.match(new RegExp('\\b' + className + '\\b'))) {
                    currentContext[currentContextIndex++] = found[k];
                }
            }
            continue; // Skip to next token
        }
        
        if (token.indexOf('#') > -1) {
            // Token is an ID selector
            var bits = token.split('#');
            var tagName = bits[0];
            var id = bits[1];
            var element = document.getElementById(id);
            if (tagName && element.nodeName.toLowerCase() != tagName) {
                // tag with that ID not found, return false
                return new Array();
            }
            // Set currentContext to contain just this element
            currentContext = new Array(element);
            continue; // Skip to next token
        }
        
        // Code to deal with attribute selectors
        if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
            var tagName = RegExp.$1;
            var attrName = RegExp.$2;
            var attrOperator = RegExp.$3;
            var attrValue = RegExp.$4;
            if (!tagName) {
                tagName = '*';
            }
            // Grab all of the tagName elements within current context
            var found = new Array;
            var foundCount = 0;
            for (var h = 0; h < currentContext.length; h++) {
                var elements;
                if (tagName == '*') {
                    elements = getAllChildren(currentContext[h]);
                } else {
                    elements = currentContext[h].getElementsByTagName(tagName);
                }
                for (var j = 0; j < elements.length; j++) {
                    found[foundCount++] = elements[j];
                }
            }
            currentContext = new Array;
            var currentContextIndex = 0;
            var checkFunction; // This function will be used to filter the elements
            switch (attrOperator) {
                case '=': // Equality
                    checkFunction = function(e){
                        return (e.getAttribute(attrName) == attrValue);
                    };
                    break;
                case '~': // Match one of space seperated words 
                    checkFunction = function(e){
                        return (e.getAttribute(attrName).match(new RegExp('\\b' + attrValue + '\\b')));
                    };
                    break;
                case '|': // Match start with value followed by optional hyphen
                    checkFunction = function(e){
                        return (e.getAttribute(attrName).match(new RegExp('^' + attrValue + '-?')));
                    };
                    break;
                case '^': // Match starts with value
                    checkFunction = function(e){
                        return (e.getAttribute(attrName).indexOf(attrValue) == 0);
                    };
                    break;
                case '$': // Match ends with value - fails with "Warning" in Opera 7
                    checkFunction = function(e){
                        return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length);
                    };
                    break;
                case '*': // Match ends with value
                    checkFunction = function(e){
                        return (e.getAttribute(attrName).indexOf(attrValue) > -1);
                    };
                    break;
                default:
                    // Just test for existence of attribute
                    checkFunction = function(e){
                        return e.getAttribute(attrName);
                    };
            }
            currentContext = new Array;
            var currentContextIndex = 0;
            for (var k = 0; k < found.length; k++) {
                if (checkFunction(found[k])) {
                    currentContext[currentContextIndex++] = found[k];
                }
            }
            // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
            continue; // Skip to next token
        }
        
        // If we get here, token is JUST an element (not a class or ID selector)
        tagName = token;
        var found = new Array;
        var foundCount = 0;
        for (var h = 0; h < currentContext.length; h++) {
            var elements = currentContext[h].getElementsByTagName(tagName);
            for (var j = 0; j < elements.length; j++) {
                found[foundCount++] = elements[j];
            }
        }
        currentContext = found;
    }
    return currentContext;
}


function checkInput(){
	var obj = {};	
	
	//check  text input is null or not
	//checkInputChoice(byClass("required",document, "input"));
	obj.isNull = function(axInputText){		
		var lxInputText = axInputText;
		for(var i=0; i<lxInputText.length; i++){
			var leInputText = lxInputText[i];
			if(trim(leInputText.value) == ""){
				if(obj.nullError){
					obj.nullError(leInputText);
				}
				return false;
			}
		}
		return true;
	}
	//
	//checkInputChoice(byClass(lsWrapperClass));
	obj.checkChoice = function(axInputWrapper){
		var liMax = Math.INFINITY;
		var lxInputWrapper = axInputWrapper;
		
		for(var i=0; i<lxInputWrapper.length; i++){
			var leInputWrapper = lxInputWrapper[i];
			var liTotalChecked = getTotalChecked(leInputWrapper);
			if(leInputWrapper.getAttribute("max") != ""){
				liMax = parseInt(leInputWrapper.getAttribute("max"));
			}else{
				liMax = Math.INFINITY;
			}
			if(liTotalChecked > liMax){			
				return false;
			}else if(liTotalChecked == 0){
				if(obj.nullError){
					obj.nullError(leInputWrapper);
				}			
				return false;			
			}
		}
		return true;		
	}
	
	// keep checked checkbox below maximum 
	obj.listenCheckbox = function(axInputWrapper){
		for(var i=0; i<axInputWrapper.length; i++){
			var leInputWrapper = axInputWrapper[i];
			var lxInput = leInputWrapper.getElementsByTagName("input");
			var liMax = Math.INFINITY;
			if(leInputWrapper.getAttribute("max") != null){
				liMax = parseInt(leInputWrapper.getAttribute("max"));
			}
		
			for(var j=0; j<lxInput.length; j++){
				var leNode = lxInput[j];
				if(leNode.type == "checkbox"){
					addEvent(leNode,"click",clickCheckboxHandler(leInputWrapper,liMax));	
				}
			}
			
		}		
		function clickCheckboxHandler(aeNode,aiMax){
			return function(){
				var lxInput = aeNode.getElementsByTagName("input");
				var liChecked = getTotalChecked(aeNode);
				if(liChecked >= aiMax){
					for(var i=0;i<lxInput.length;i++){
						var leInput = lxInput[i];
						if(leInput.type == "checkbox" && leInput.checked == false){
							leInput.disabled = true;
						}
					}
				}else{
					for(var i=0;i<lxInput.length;i++){
						var leInput = lxInput[i];
						if(leInput.checked == false){
							leInput.disabled = false;
						}
					}
				}
				
			}	
		}		
	}
	return obj;
	
	function getTotalChecked(aeNode){
		if(!aeNode){
			return -1;
		}
		var lxInput = aeNode.getElementsByTagName("input");
		var cnt = 0;
		for(var i=0; i<lxInput.length; i++){
			var leNode = lxInput[i];
			if((leNode.type == "radio" || leNode.type == "checkbox") && leNode.checked){
				cnt++;
			}
		}
		return cnt;	
	}
	function addEvent(aeTag, asEvt, afHandler){
	    if (!aeTag) {
	        return false;
	    }
	    if (navigator.userAgent.indexOf("IE") != -1) {
	        aeTag.attachEvent("on" + asEvt, afHandler);
	    } else {
	        aeTag.addEventListener(asEvt, afHandler, false);
	    }
	}	
	function trim(asStr){
	    asStr = asStr == null ? "" : asStr;
	    return asStr.replace(/(^\s*)|(\s*$)/g, "");
	}	
}